package com.webshop.DataBase;

import com.webshop.JavaBean.User;
import com.webshop.service.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/UserServlet")
public class UserServlet extends javax.servlet.http.HttpServlet {
    private static final String TAG = "UserServlet";
    private UserService us = new UserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(TAG + "service");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String method = request.getParameter("method");
        System.out.println(method);

        switch (method)
        {
            case "regist":
                regist(request, response);
                break;
            case "isHave":
                isHave(request, response);
                break;
            case "login":
                login(request, response);
                break;
            case "getInfo":
                getInfo(request, response);
                break;
            case "justifyEmail":
                justifyEmail(request, response);
                break;
            case "changePassword":
                changePassword(request, response);
                break;
            case "test":
                testde(request, response);
                break;
            case "modify":
                modifyinfo(request, response);
                default:
                    break;
        }

    }

    /**
     * 修改用户信息。
     * @param req
     * @param resp
     */
    private void modifyinfo(HttpServletRequest req, HttpServletResponse resp) {
             HttpSession session = req.getSession();
            String name =  String .valueOf(session.getAttribute("name"));
            String phone=req.getParameter("phone");
            String email=req.getParameter("email");
            System.out.println(name+phone+email);
            try {
               us.updataper(phone,email,name);
                resp.sendRedirect("/html/gerenzhongxin.jsp");
            }catch (Exception e){
                System.out.println("flase");
            }

        }


    private void testde(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session=request.getSession();
        Object obj = session.getAttribute("name");
        String name = String.valueOf(obj);
        System.out.println(name);
        /*PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write("\"code\":1");*/

    }

    /**
     * ajaix 验证用户名是否存在
     * @param request
     * @param response
     * @throws Exception
     */
    private void isHave(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        System.out.println(name);
        System.out.println(email);
        System.out.println(phone);

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean flag;
        if(name!=null) {
            flag = us.isHavaName(name);
        } else if (email != null) {
            flag = us.isHavaEmail(email);
        }else{
            flag = us.isHavaPhone(phone);
        }

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (flag) {
            // "code":1
            //说明信息已存在，需要更换
            jsonObject.put("code", 1);
        }else {
            jsonObject.put("code", 2);
        }
        jsonArray.add(jsonObject);
        writer.write(jsonArray.toString());
    }

    /**
     * 修改密码
     * @param request
     * @param response
     */
    private void changePassword(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        us.changePassword(name, password);

        //这里可能需要对密码进项相关的操作。
         //返回首页，并且是未登录状态
        String path = request.getContextPath();
        try {
            response.sendRedirect(path+"/html/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 找回密码验证邮箱
     * @param request
     * @param response
     */
    private void justifyEmail(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        boolean flag = us.justifyEmail(name, email);
        if (flag) {
            String EmailMsg = "邮箱通过";
            String JustifyName = name;
            request.setAttribute("JustifyName", JustifyName);
            request.setAttribute("emailPass", EmailMsg);
        }
        try {
            request.getRequestDispatcher("/html/forget-password.jsp").forward(request,response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @param response
     */
    private void getInfo(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进来了");
        String name = request.getParameter("name");
        System.out.println(name);
        User temp = us.getUserInfo(name);
        System.out.println(temp);
        PrintWriter writer = null;
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(temp);
        try {
            writer=response.getWriter();
            writer.write(jsonArray.toString());
            //request.getRequestDispatcher("/test.jsp").forward(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String path = request.getContextPath();
        System.out.println(path);
        //这里很容易看出，重定向是通过Session 来传递信息，这个信息的声明周期是浏览器打开期间。
        try {
            if(us.login(name,password)){
                HttpSession session = request.getSession();
                session.setAttribute("name", name);
                User userInfo = us.getUserInfo(name);
                String email = userInfo.getMail();
                String phone = userInfo.getPhone();
                session.setAttribute("userphone", phone);
                session.setAttribute("useremail",email);
                System.out.println(name+"登录成功");
                response.sendRedirect(path+"/GoodsServlet?method=ishot");
            }else {
                String ErrorMsg = "用户名或密码错误";
                request.setAttribute("name",name);
                request.setAttribute("password",password);
                request.setAttribute("Err", ErrorMsg);
                System.out.println(name+"failure");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }

    }

    /**
     * 注册
     * @param request
     * @param response
     */
    private void regist(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        User user = new User(name, password, phone, email, sex);
        String path = request.getContextPath();
        us.savedUser(user);
        try {
            response.sendRedirect(path+"/html/index.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
